package com.northpool.operator.statistics.dataset.serve;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.common.database.DatabaseUtils;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.type.TypeEnum;
import com.northpool.operator.utils.ServeOperatorHelper;
import com.northpool.resources.datasource.IDataSource;
import com.northpool.resources.datasource.db.DbDataSource;

import java.util.Map;

@OperatorInfo(
        ref = "SqlQueryServeOperator",
        name = "SQL查询服务",
        version = "1.0.0"
)
public class SqlQueryServeOperator extends ServeOperatorHelper {

    @InputParams({
            @InputParam(ref = "port", type = TypeEnum.NUMBER, name = "服务端口", desc = "服务端口", value = "8080"),
    })
    public SqlQueryServeOperator(ParamTool paramTool) {
        super(paramTool.getNumber("port").intValue());
    }

    public static void main(String[] args) throws Exception {
        OperatorTestBuild.execute(SqlQueryServeOperator.class, TestParamBuilder.aBuilder()
                .param("port", "8080")
                .build());
    }

    @Override
    public void execute(ParamTool paramTool) throws Exception {
        this.addEndpoint("/query", Method.POST, session -> {
            Map<String, Object> bodyParams = session.getBodyParams();
            String dataSourceId = bodyParams.get("dataSourceId").toString();
            String dataSourceStr = DatabaseUtils.getDataSourceJson(dataSourceId);
            try {
                DbDataSource datasource = (DbDataSource) IDataSource.fromJSON(dataSourceStr);
                String strSql= bodyParams.get("sql").toString();
                return datasource.queryBySql(strSql, null);
            } catch (Exception ex) {
                this.error(ExceptionUtil.getMessage(ex));
            }
            return null;
        });
    }
}
